package com.example.photo_sharing.page.navigation;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.NetworkOnMainThreadException;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.View;
import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.photo_sharing.R;
import com.example.photo_sharing.global.App;
import com.example.photo_sharing.page.adapter.listItemAdapter;
import com.example.photo_sharing.page.others.Detailed;
import com.example.photo_sharing.tool.Impl.UserInfoSPImpl;
import com.example.photo_sharing.entity.FindList;
import com.example.photo_sharing.entity.FindListItem;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Index extends Fragment {
    private App app;
    private FindList fl = new FindList();

    private RecyclerView recyclerView; //定义ReclerView控件
    private View root;//定义view来设置fragment中的layout
    private ArrayList<FindListItem> goodsEntities = new ArrayList<>();
    private listItemAdapter myadpater;
    private SwipeRefreshLayout swipeRefreshLayout;

    private String userId;
    private boolean sign_of_empty = true;
    private boolean sign_of_login = true;

    private SharedPreferences sharedPreferences;
    private UserInfoSPImpl usp;

    public Index() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        app = (App)getActivity().getApplication();
        sharedPreferences = getActivity().getSharedPreferences("userInfo",getActivity().MODE_PRIVATE);
        usp = new UserInfoSPImpl(sharedPreferences);

        sign_of_login = usp.isLogin();
        System.out.println(sign_of_login);
        if(sign_of_login){
            userId = usp.getUserId();
            System.out.println(userId);
        }

        get();


    }

    public View onCreateView(@NonNull LayoutInflater inflater,ViewGroup container,Bundle saveInstanceState){

        root = inflater.inflate(R.layout.navigation_index,container,false);

//        swipeRefreshLayout = (SwipeRefreshLayout)root.findViewById(R.id.index_refresh);
//        handleDownPullUpdate();

//        handleUpLoadMore();


        return root;
    }


    @Override
    public void onResume() {
        super.onResume();
        app.setDelay(300);
        initRecyclerView();
    }

    //获取发现列表的内容
    private void get(){

        new Thread(() -> {
            System.out.println("this is get");
            // url路径
            String url = "http://47.107.52.7:88/member/photo/focus?"
                    +"current="+app.getCurrent()
                    +"&size="+app.getSize()
                    +"&userId="+userId;

            // 请求头
            Headers headers = new Headers.Builder()
                    .add("Accept", "application/json, text/plain, */*")
                    .add("appId", app.getAppId())
                    .add("appSecret", app.getAppSecret())
                    .build();

            //请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .get()
                    .build();
            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callback);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            }
        }).start();
    }

    private final Callback callback = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, IOException e) {
            e.printStackTrace();
            System.out.println("失败");
        }
        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            System.out.println("this is get2");

            String responseData = response.body().string();
            System.out.println(responseData);
            JSONObject jsonObject  = JSONObject.parseObject(responseData).getObject("data", JSONObject.class);

            if(jsonObject == null){
                return;
            }
            else{
                sign_of_empty = false;
            }

            JSONArray jsonArray = jsonObject.getJSONArray("records");

            fl.setCurrent(jsonObject.getInteger("total"));
            fl.setSize(jsonObject.getInteger("size"));
            fl.setTotal(jsonObject.getInteger("current"));

            //将获取的图片链接存入数据中
            ArrayList<FindListItem> fli = new ArrayList<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject object = jsonArray.getJSONObject(i);
                FindListItem jo = JSON.toJavaObject(object,FindListItem.class);
                JSONArray ja = object.getJSONArray("imageUrlList");
                List<String> img_url = ja.toJavaList(String.class);
                jo.setImageUrlList(img_url);
                fli.add(i,jo);
            }
            fl.setRecords(fli);
            goodsEntities = fli;
            System.out.println(goodsEntities.size());
            System.out.println("成功");
        }
    };

    private void initRecyclerView() {
        recyclerView = (RecyclerView)root.findViewById(R.id.index_recyclerview);
        myadpater = new listItemAdapter(getActivity(),goodsEntities);
        recyclerView.setAdapter(myadpater);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false));

        recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(),DividerItemDecoration.VERTICAL));

        myadpater.setOnItemClickListener(new listItemAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view, FindListItem data) {
                if(usp.isLogin()){
                    Intent intent = new Intent(getActivity(), Detailed.class);
                    intent.putExtra("shareId",data.getId());
                    intent.putStringArrayListExtra("urls",(ArrayList<String>) data.getImageUrlList());
                    intent.putExtra("data",data);
                    startActivity(intent);
                }
                else{
                    Toast.makeText(getActivity(),"请先登录",Toast.LENGTH_LONG).show();
                }
            }
        });
    }
}
